$(document).ready(function() {
    loadData(); // 页面加载时加载数据
});

function loadData() {
    $.ajax({
        url: "/poster/init",
        type: "GET",
        success: function(response) {
            var type = $("#type");
            $.each(response, function(index, item) {
                dropdown.append($("<option />").val(item.type).text(item.name));
            });
        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });
}

function validateFileType() {
    var fileInput = document.getElementById("file");
    var fileName = fileInput.value;
    var allowedExtensions = ['.jpg', '.jpeg', '.png'];
    var fileExtension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();

    if (!allowedExtensions.includes(fileExtension)) {
        alert("请上传图片格式文件");
        return false;
    }
    return true;
}

function showPreview() {
    var select = document.getElementById("type");
    var previewImage = document.getElementById("previewImage");

    if (select.value === "1") {
        previewImage.src = "/time.jpg";
    } else if (select.value === "2") {
        previewImage.src = "/red.jpg";
    } else if (select.value === "3") {
        previewImage.src = "/write.jpg";
    } else if (select.value === "4") {
        previewImage.src = "/year9999.jpg";
    } else {
        previewImage.src = "/year.jpg"; // 如果没有匹配的值，则清空预览图片
    }
}

function showImage(select) {
    var selectedValue = select.value;
    var selectedOption = select.options[select.selectedIndex];
    var imageUrl = selectedOption.getAttribute('data-image');
    document.getElementById('previewImage').src = imageUrl;
}

function showPreviewSelected(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('previewImgImage').src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$('#uploadForm').submit(function(event) {
    event.preventDefault();
    var formData = new FormData(this);

    $.ajax({
        url: '/poster',
        type: 'POST',
        data: formData,
        success: function(response) {
            alert(response)
            $('#displayImage').attr('src', response.url);
        },
        error: function(xhr, status, error) {
            console.error(error);
        },
        cache: false,
        contentType: false,
        processData: false
    });
});